const { UNKNOWN_ERROR } = require("../config/error-constants");
const momentService = require("../service/moment.service");
const { to } = require("../utils");
class MomentController {
    async create(ctx, next) {
        // 1.获取动态内容
        const { content } = ctx.request.body;
        // 2.动态由谁发布（token=>id/name）
        const { id } = ctx.user;
        // 3.将动态相关的数据保存到数据库
        const [error, resp] = await to(momentService.create(content, id));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }

        ctx.body = {
            code: 0,
            message: "创建用户动态成功~",
        };
    }

    async list(ctx, next) {
        const { size, offset } = ctx.query;
        const [error, resp] = await to(momentService.list(size, offset));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }

        ctx.body = {
            code: 0,
            data: resp,
        };
    }

    async detail(ctx, next) {
        const { momentId } = ctx.params;
        const [error, resp] = await to(momentService.detail(momentId));
        if (error) {
            console.log("error", error);
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }

        ctx.body = {
            code: 0,
            data: resp[0],
        };
    }

    async update(ctx, next) {
        const { momentId } = ctx.params;
        const { content } = ctx.request.body;
        const [error, resp] = await to(momentService.update(content, momentId));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }

        ctx.body = {
            code: 0,
            message: "修改动态成功~",
        };
    }

    async remove(ctx, next) {
        const { momentId } = ctx.params;
        const [error, resp] = await to(momentService.remove(momentId));
        if (error) {
            return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
        }

        ctx.body = {
            code: 0,
            message: "删除动态成功~",
        };
    }

    async addLabels(ctx, next) {
        const { momentId } = ctx.params;
        const labels = ctx.labels;
        // 遍历labels
        for (const label of labels) {
            // 判断moment_label表中是否已经存在momentId和labelId关系记录
            // 如果存在直接跳过
            // 如果不存在就创建
            const { id } = label;
            const [isExistLabelIdError, isExistLabelId] = await to(momentService.hasLabelId(momentId, id));
            if (isExistLabelIdError) {
                return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
            }
            if (isExistLabelId) continue;
            const [error, resp] = await to(momentService.addLabels(momentId, id));
            if (error) {
                return ctx.app.emit("error", UNKNOWN_ERROR, ctx);
            }
        }

        ctx.body = {
            code: 0,
            message: "动态添加标签成功~",
        };
    }
}

module.exports = new MomentController();
